import unittest
import time
from BeautifulReport import BeautifulReport
import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def get_NewReport(testreport):
    # 获取testreport 目录下的文件返回一个list
    dirs = os.listdir(testreport)
    # 对文件list 进行排序 进行增序排列
    dirs.sort()
    # 获取序列最后一个元素，即最大的一个元素。
    newreportname = dirs[-1]
    print('The new report name: {0}'.format(newreportname))
    file_new = os.path.join(testreport, newreportname)
    print(file_new)
    return file_new


def send_Mail(file_new):

    smtpserver = "smtp.163.com"
    user = "18311447530@163.com"
    sender = "18311447530@163.com"
    pwd = "an1234"
    receiver = "18311447530@163.com"
    port = 25
    f = open(file_new, 'rb')
    # 读取测试报告正文
    mail_body = f.read()
    f.close()
    msg = MIMEMultipart()
    msg['Subject'] = '测试报告'
    msg_file = MIMEText(mail_body, 'html', 'utf-8')
    msg_file['Content-Type'] = 'application/octet-stream'
    msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"'
    msg.attach(msg_file)
    # 定义发件人，如果不写，发件人为空
    msg['From'] = user
    # 定义收件人，如果不写，收件人为空
    msg['To'] = receiver
    server = smtplib.SMTP()
    server.connect(smtpserver, port)
    server.login(user, pwd)
    server.sendmail(user, receiver, msg.as_string())
    server.close()

# 获取系统当前时间
now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
# 设置报告名称格式
HtmlFile = now + "report.html"
if __name__ == '__main__':
    test_suite = unittest.TestLoader().discover('testsuites')
    runner = BeautifulReport(test_suite)
    runner.report(filename=HtmlFile,description='测试报告', log_path='F:\\C++\\untitled3\\reports')
    new_report = get_NewReport("F:\\C++\\untitled3\\reports")
    send_Mail(new_report)
